package com.powernode.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;

import java.time.Duration;

/**
 * redis配置类
 * json序列化模块 : 将Redis中的数据序列化为JSON字符串，并使用基于JSON的对象模型进行解码
 */
@Configuration
public class RedisCacheConfig {

    /**
     * 创建redis缓冲配置类
     * 进行redis配置
     * 设置value序列化格式
     * 设置过期时间
     * 禁用value使用空值
     * fromSerializer : Creates a RedisSerializationContext.SerializationPair adapter given RedisSerializer.
     * entryTtl : Set the ttl to apply for cache entries. Use Duration.ZERO to declare an eternal cache.
     * disableCachingNullValues : Disable caching null values
     * @return
     */
    @Bean
    public RedisCacheConfiguration redisCacheConfiguration() {
        // rediscache配置类
        RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig();
        // redischche配置
        redisCacheConfiguration
                .serializeValuesWith(RedisSerializationContext
                                .SerializationPair
                                .fromSerializer(RedisSerializer.json()))
                .entryTtl(Duration.ofHours(24))  // 过期时间1天
                .disableCachingNullValues();  // 禁用value使用空值
        return redisCacheConfiguration;
    }
}
